package br.com.unisinos.unitunes.framework.conexao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DaoHelper {
    
    private static final ThreadLocal<Connection> context = new ThreadLocal<Connection>();
    
    private Connection conexao;
    public Statement statement;
    public ResultSet resultset;
    
    private final String driver = "oracle.jdbc.driver.OracleDriver";
    private final String url = "jdbc:oracle:thin:@localhost:1521:XE";  
    private final String usr = "UNITUNES";  
    private final String pwd = "UNITUNES";
    
    
    public Connection getConnection() throws SQLException{
        try{
            Class.forName(driver);
            conexao = DriverManager.getConnection(url, usr, pwd);
        }
        catch(ClassNotFoundException erro){
            erro.printStackTrace();
        }
        return conexao;
    }
    
    public void beginTrasaction() throws SQLException{
        conexao = getConnection();
        conexao.setAutoCommit(false);
        context.set(conexao);
    }
    
    public void endTransaction() throws SQLException{
        commit(getConnectionFromContext());
        
    }
    
    public void commit(Connection conexao) throws SQLException{
        conexao.commit();
    }
    
    public Connection getConnectionFromContext() throws SQLException{
        conexao = context.get();
        if(conexao == null) throw new SQLException("Transação inválida!");
        if (conexao.isClosed()) throw new SQLException ("Transação inválida, a conexão está fechada!");
        return conexao;
    }
    
    public void release(Statement statement){
        if(statement == null)
            return;
        try {
            statement.close();
        }
        catch (SQLException erro) {}
    }
    
    public void release(Connection conexao){
        if(conexao == null)
            return;
        try {
            conexao.close();
        }
        catch (SQLException erro) {}
    }
    
    public void release(ResultSet resultset){
        if(resultset == null)
            return;
        try {
            resultset.close();
        }
        catch (SQLException erro) {}
    }
    
    public void releaseAll(Connection conn, Statement stmt){
        release(stmt);
        release(conn);
    }
    
    public void releaseAll(Connection conn, Statement stmt, ResultSet rset){
        release(rset);
        releaseAll(conn, stmt);
    }
    
}
